package problems.daily;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 811. 子域名访问计数
 * <p>https://leetcode.cn/problems/subdomain-visit-count/</p>
 *
 * @author habitplus
 * @since 9:51, 2022/10/5
 */
public class DT811 {

    public List<String> subdomainVisits(String[] cpdomains) {
        List<String> ret = new ArrayList<>();
        if (cpdomains == null || cpdomains.length < 1) return ret;

        HashMap<String, Integer> map = new HashMap<>();
        for (String domain : cpdomains) {
            parse(map, domain);
        }

        String k;
        int cnt;
        for (Map.Entry<String, Integer> en : map.entrySet()) {
            k = en.getKey();
            cnt = en.getValue();
            ret.add(String.format("%d %s", cnt, k));
        }

        return ret;
    }

    private void parse(HashMap<String, Integer> cntMap, String domain) {
        if (domain == null || domain.length() < 1) return;

        String[] ss = domain.split(" ");
        int cnt = Integer.parseInt(ss[0]);

        int k = 0;
        int n = ss[1].length();
        String keyStr;

        while (-1 < k && k < n) {
            keyStr = ss[1].substring(k == 0 ? k : k + 1);
            cntMap.put(keyStr, cntMap.getOrDefault(keyStr, 0) + cnt);
            k = ss[1].indexOf('.', k + 1);
        }
    }
}
